/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package strategies;

import common.Application;
import common.ParamStorage;
import html.XHtmlFormatter;
import localization.Localization;
import parsers.ExtensionPanelParser;
import templates.ExtensionTemplate;
import templates.Template;

/**
 *
 * @author Alejandro
 */
public class ExtensionPanelStrategy implements Strategy {

    private boolean ignoreCustomStrategy = false;

    public ExtensionPanelStrategy(boolean ignoreCustomStrategy) {
        this.ignoreCustomStrategy = ignoreCustomStrategy;
    }

    @Override
    public void execute(WebContext ctx) {
        XHtmlFormatter provider = ctx.getWebFormatter();
        ParamStorage storage = ctx.getParamStorage();
        short uid = ctx.getUid();
        if (uid != 0) {
            Template t = Application.getInstance().getTemplate(uid);
            if (t.hasExtensions()) {
                provider.startDiv("extensionToolbar");
                Iterable<ExtensionTemplate> extensions = t.getExtensionTemplateCollection();
                for (ExtensionTemplate et: extensions) {
                    provider.startDiv("", "extensionTitle");
                    provider.writeH2(Localization.getString(et.getName()));
                    provider.endDiv();
                    provider.startDiv();

                    ExtensionPanelParser parser = new ExtensionPanelParser(et.getPanel().getText());
                    ExtensionPanelParser.State state = parser.run();
                    StringBuilder builder = new StringBuilder();
                    while (state != ExtensionPanelParser.State.Finished) {
                        switch (state) {
                            case Text:
                                builder.append(parser.getChar());
                                break;
                            case LocalizedString:
                                builder.append(Localization.getString(parser.getArgument()));
                                break;
                            case ControlName:
                                builder.append(parser.getArgument());
                                break;
                            case ReplaceName:
                                if (storage.hasParam(parser.getArgument()) && !ignoreCustomStrategy)
                                    builder.append(storage.getParam(parser.getArgument()));
                                break;
                        }
                        state = parser.run();
                    }

                    provider.echo(builder.toString());
                    provider.endDiv();
                }
                provider.endDiv();
            }
        }
    }
}
